package com.example.providertest;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private String newId;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button add_data = findViewById(R.id.add_data);

        add_data.setOnClickListener(v -> {
            Uri uri = Uri.parse("content://com.example.databasetest.provider/book");
            ContentValues values = new ContentValues();
            values.put("name", "A Clash of Kings");
            values.put("author", "George Martin");
            values.put("pages", 1040);
            values.put("price", 22.85);
            Uri newUri = getContentResolver().insert(uri, values);
            newId = newUri.getPathSegments().get(1);
        });

        Button query_data = findViewById(R.id.query_data);
        query_data.setOnClickListener(v -> {
            Uri uri = Uri.parse("content://com.example.databasetest.provider/book");
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (null != cursor){
                while (cursor.moveToNext()){
                  @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
                  @SuppressLint("Range")  String author = cursor.getString(cursor.getColumnIndex("author"));
                  @SuppressLint("Range")  int pages = cursor.getInt(cursor.getColumnIndex("pages"));
                  @SuppressLint("Range")  double price = cursor.getDouble(cursor.getColumnIndex("price"));
                    Log.d(TAG, "name是" + name);
                    Log.d(TAG, "author是" + author);
                    Log.d(TAG, "pages是" + pages);
                    Log.d(TAG, "price是" + price);
                }
            }
        });

        Button update_data = findViewById(R.id.update_data);
        update_data.setOnClickListener(v -> {
            Uri uri = Uri.parse("content://com.example.databasetest.provider/book/" + newId);
            ContentValues values = new ContentValues();
            values.put("name", "A storm of swords");
            values.put("pages", 1216);
            values.put("price", 24.05);
            getContentResolver().update(uri, values, null, null);
        });

        Button delete_data = findViewById(R.id.delete_data);
        delete_data.setOnClickListener(v -> {
            Uri uri = Uri.parse("content://com.example.databasetest.provider/book/" + newId);
            getContentResolver().delete(uri,null,null);
        });
    }
}